<?php

/**
 * Klasa do obsługi SQLite dla TempaQ2
 * 
 * @author Karol Kuczok (karol@kuczok.net)
 * @author Tomasz Drwięga (tomusdrw@gmail.com)
 * 
 * @package TempaQ2
 */


class sqlite {
	
	private static $resource;
	private static $tables=array();
	
	public static function open() {
		self::$resource = sqlite_popen(CONF_TABLE_PREFIX.'sqlite');
		$res = self::query('SELECT name FROM (SELECT * FROM sqlite_master UNION ALL SELECT * FROM sqlite_temp_master) WHERE type="table" ORDER BY name');
		$res = self::fetch_all($res);
		foreach ($res as $v) self::$tables[]=$v['name'];
	}
	
	public static function fetchSQL($sql) {
		$result = self::query($sql);
		if ($result==FALSE) return array();
		$rows = self::fetch_all($result);
		return $rows;
	}
	
	public static function close() {
		sqlite_close(self::$resource);
	}
	
	public static function query($sql) {
		echo 'SQL: '.$sql."\n"; flush();
		return sqlite_query(self::$resource,$sql);
	}
	
	public static function fetch_all($result) {
		return sqlite_fetch_all($result);
	}
	
	public static function getTables() {
		return self::$tables;
	}
	
	public static function create($table,$struct) {
		if (!is_array($struct)) return false;
		if (in_array($table,self::$tables)) return true;
		$sql='CREATE TABLE '.$table.' (';
		$is_first=true;
		foreach ($struct as $k => $v) {
			if (!$is_first) $sql.=',';
			$is_first=false;
			$sql.=$k.' ';
			switch ($struct) {
				case 'INT':
					$sql.=' INT';
					break;
				case 'VARCHAR':
					$sql.='VARCHAR(255)';
					break;
				case 'TEXT':
					$sql.='TEXT';
					break;
				case 'INT1': case 'INT 1':
					$sql.=' INT DEFAULT 1';
					break;
				case 'INT0': case 'INT 0':
					$sql.=' INT DEFAULT 0';
					break;
				default:
					$sql.='TEXT';
			}

		}
		
		$sql.=')';
		self::query($sql);
		self::$tables[]=$table;
		return true;
	}
	
	public static function insert($table,$row) {
		if (!is_array($wartosci)) return false;
		$vars=array();
		$params=array();
		foreach ($wartosci as $k => $v) {
			$vars[]=$k;
			if ($noquotes) $params[]=$v;
			else $params[]='"'.$v.'"';
		}
		$sql='INSERT INTO '.$tabela.' ('.implode(',',$vars).') VALUES ('.implode(',',$params).')';
		return self::query($sql);
	}
	
}

sqlite::open();

sqlite::create('config',array(
	'id'=>'VARCHAR',
	'valute'=>'TEXT',
));

sqlite::create('ops',array(
	'name'=>'VARCHAR',
	'ident'=>'VARCHAR',
	'autoop'=>'INT',
	'host'=>'VARCHAR',
	'pass'=>'VARCHAR',
));

sqlite::create('log',array(
	'channel'=>'VARCHAR',
	'timestamp'=>'INT',
	'nick'=>'VARCHAR',
	'ident'=>'VARCHAR',
	'msg'=>'VARCHAR',
));


?>